<?php
namespace app\common\model;

class OkrRecord extends Base
{
    /**
     * 生成OKR数据
     */
    public static function addOkr()
    {
        $isAdd = self::whereMonth('create_time')->find();
        if($isAdd) return;

        $stageArr = [1, 2, 3, 4];

        /** 本月1号0点 */
        $stageTimeFst = strtotime(date('Y-m', time()));

        /** 本月7号0点 */
        $stageTimeSec = $stageTimeFst + 6 * 86400;

        /** 本月15号0点 */
        $stageTimeThi = $stageTimeFst + 14 * 86400;

        /** 本月23号0点 */
        $stageTimeFou = $stageTimeFst + 22 * 86400;

        /** 次月1号0点 */
        $stageTimeFif = strtotime(date('Y-m-t', time())) + 86400;

        $timeArr = [1 => $stageTimeFst, 2 => $stageTimeSec, 3 => $stageTimeThi, 4 => $stageTimeFou, 5 => $stageTimeFif];

        $userList = User::getList([['section_id', 'in', self::getAchievSection()]], 0, 0, 0, 'id');

        $okrData = [];
        foreach($stageArr as $stage){
            $okrRuleInfo = RuleOkr::getFind(['stage' => $stage]);

            foreach($userList as &$info){
                $okrInfo = [
                    'user_id'     => $info['id'],
                    'invite_num'  => $okrRuleInfo['invite_num'],
                    'face_num'    => $okrRuleInfo['face_num'],
                    'pass_num'    => $okrRuleInfo['pass_num'],
                    'score_okr'   => 0,
                    'stage'       => $stage,
                    'start_time'  => $timeArr[$stage],
                    'end_time'    => $timeArr[$stage + 1] - 1,
                    'create_time' => time(),
                ];

                $okrData[] = $okrInfo;
            }
        }

        self::addAll($okrData);
    }

    /**
     * 查询单项工资构成的部门
     * @param int $type 类型（1=基本工资, 2=绩效, 3=提成, 4=福利）
     */
    public static function getAchievSection($type = 2)
    {
        $section = UserSection::getList([], 0, 0, 0, 'id, salary_type_id');

        $sectionIds = [];
        foreach($section as &$info){
            if(in_array($type, explode(',', $info['salary_type_id'])) !== false) $sectionIds[] = $info['id'];
        }

        return $sectionIds;
    }

    /**
     * 计算OKR分数
     * @param int $userId 员工ID
     * @param int $type 类型（2=邀约，3=到面，4=通过）
     */
    public static function setOkrFrac($userId, $type)
    {
        $where[] = ['user_id', '=', $userId];
        $where[] = ['stage', '=', OkrRecord::getStage()];

        $info = OkrRecord::getFind($where);
        if(!$info) return false;

        $system = getSystem();

        $fieldNum     = [2 => 'invite_num_reality', 3 => 'face_num_reality', 4 => 'pass_num_reality'];
        $fieldRuleNum = [2 => 'invite_num', 3 => 'face_num', 4 => 'pass_num'];
        $fieldRadio   = [2 => 'invite_radio', 3 => 'face_radio', 4 => 'pass_radio'];
        $fieldFrac    = [2 => 'invite_frac', 3 => 'face_frac', 4 => 'pass_frac'];

        /** 完成情况 */
        $finishRadio = rounding($info[$fieldNum[$type]] / $info[$fieldRuleNum[$type]]);
        $finishRadio = $finishRadio > 1 ? 1 : $finishRadio;

        /** 单项分数 */
        $frac = round($finishRadio * $system[$fieldRadio[$type]]);
        OkrRecord::edit(['id' => $info['id'], $fieldFrac[$type] => $frac]);

        /** 总分和等级 */
        $infoNew = OkrRecord::getFind($where);
        $fracAll = $infoNew['invite_frac'] + $infoNew['face_frac'] + $infoNew['pass_frac'];
        OkrRecord::edit(['id' => $infoNew['id'], 'score_okr' => $fracAll, 'grade_okr' => self::getGrade($fracAll)]);
    }

    /**
     * 获取等级
     * @param int $frac 总分
     */
    public static function getGrade($frac)
    {
        $list = RuleAccess::getList([], 0, 0, 0, '*', 'fraction_high DESC');

        $grade = 5;
        foreach($list as $info){
            if($frac >= $info['fraction_low']){
                $grade = $info['grade'];
                break;
            }
        }

        return $grade;
    }

    /**
     * 根据当前时间获取阶段
     */
    public static function getStage()
    {
        $time = time();

        /** 本月1号0点 */
        $stageTimeFst = strtotime(date('Y-m', time()));

        /** 本月7号0点 */
        $stageTimeSec = $stageTimeFst + 6 * 86400;

        /** 本月15号0点 */
        $stageTimeThi = $stageTimeFst + 14 * 86400;

        /** 本月23号0点 */
        $stageTimeFou = $stageTimeFst + 22 * 86400;

        /** 次月1号0点 */
        $stageTimeFif = strtotime(date('Y-m-t', time())) + 86400;

        if($time >= $stageTimeFst && $time < $stageTimeSec){
            return 1;
        }else if($time > $stageTimeSec && $time < $stageTimeThi){
            return 2;
        }else if($time > $stageTimeThi && $time < $stageTimeFou){
            return 3;
        }else if($time > $stageTimeFou && $time < $stageTimeFif){
            return 4;
        }else{
            return 0;
        }
    }


    public function getStartTimeAttr($val)
    {
        if(!$val) return '';
        return date('Y-m-d', $val);
    }

    public function getEndTimeAttr($val)
    {
        if(!$val) return '';
        return date('Y-m-d', $val);
    }
}